package ch.qos.logback.classic.log4j2;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;

import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.StackTraceElementProxy;

public class ThrowableProxy implements IThrowableProxy {
	private JsonNode json;
	static StackTraceElementProxy[] emptyArray = new StackTraceElementProxy[0];

	public ThrowableProxy(JsonNode json) {
		this.json = json;
	}

	@Override
	public String getMessage() {
		if (json.has("message")) {
			return json.get("message").asText();
		}
		return null;
	}

	@Override
	public String getClassName() {
		return json.get("name").asText();
	}

	@Override
	public StackTraceElementProxy[] getStackTraceElementProxyArray() {
		JsonNode jsonNode = json.get("extendedStackTrace");
		if (jsonNode != null && jsonNode.isArray()) {
			ArrayNode arrayNode = (ArrayNode) jsonNode;
			if (arrayNode.size() > 0) {
				StackTraceElementProxy[] arr = new StackTraceElementProxy[arrayNode.size()];
				for (int i = 0; i < arr.length; i++) {
					jsonNode = arrayNode.get(i);
					StackTraceElement ste = new StackTraceElement(jsonNode.get("class").asText(),
							jsonNode.get("method").asText(), jsonNode.get("file").asText(),
							jsonNode.get("line").asInt());
					arr[i] = new StackTraceElementProxy(ste);
				}
				return arr;
			}
		}
		return emptyArray;
	}

	@Override
	public int getCommonFrames() {
		return 0;
	}

	@Override
	public IThrowableProxy getCause() {
		if (json.has("cause")) {
			return new ThrowableProxy(json.get("cause"));
		}
		return null;
	}

	@Override
	public IThrowableProxy[] getSuppressed() {
		return null;
	}

	@Override
	public boolean isCyclic() {
		return false;
	}

}
